package com.ipemon.server;

import java.io.IOException;
import java.net.SocketException;
import java.util.List;

import com.ipemon.exception.DataNotSentException;
import com.ipemon.model.Foret;

public class ForetNet implements CallBack{
	
	private PseudoTCPoverUDP pseudoTCP = null;
	private Foret foret = new Foret();

	private boolean dataIn = false;
	private List<String> data = null;
	 
	
	public ForetNet(int port) throws SocketException {
		PseudoTCPoverUDP.setListeningPort1(port);
		pseudoTCP = PseudoTCPoverUDP.getFirstInstance();
	}
	
	public ForetNet(PseudoTCPoverUDP pseudoTCP){
		this.pseudoTCP = pseudoTCP;
	}

	
	public synchronized void listen() {
		try {
			pseudoTCP.receiveData(this);

			while(!dataIn) {
				wait();				
			}

			process();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		listen();
	}
	
	public void process() {
		
		String protocol[] = data.get(0).split(" ");

		if(protocol[0].equalsIgnoreCase("nouveau")) {
			
			String newipemonString = foret.getIpemonStream(foret.generateIpemon());
			
			try {
				pseudoTCP.sendData("DONNE " + newipemonString);

				System.out.println("Sent: " + newipemonString);
				
			} catch (IOException exp ) {
				System.out.println("New ipemon sending failed due to IO Failure");
			} catch (DataNotSentException e) {
				System.out.println("New ipemon sending failed");
			}
			
		}
		
		dataIn = false;
		data = null;
	}

	@Override
	public synchronized void callIfReceived(int type, Object data) {
		this.data = (List<String>) data;
		dataIn = true;
		notifyAll();
	}
	
	public static void main(String[] args) throws SocketException{
		
		ForetNet foret;
		
		if(args.length > 0) {
			
			if (args[0].equals("--port")) {
				int port = Integer.valueOf(args[1]);
				foret = new ForetNet(port);				
			}
			
			else {
				foret = new ForetNet(9000);
			}
			
		} else {
			foret = new ForetNet(9000);
		}
			
		foret.listen();
		
	}


}
